package com.yiren.dbaa.module.exam.view.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.yiren.backstage.currency.bean.CarStateBean;
import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.utils.DateUtil;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.dbaa.R;
import com.yiren.dbaa.constant.NumberConstant;
import com.yiren.dbaa.constant.PointCode;
import com.yiren.dbaa.currency.dialog.CommonDialog;
import com.yiren.dbaa.module.exam.view.adapter.DjCarSignalAdapter;
import com.yiren.dbaa.module.exam.view.adapter.DjGradesAdapter;
import com.yiren.dbaa.module.exam.view.adapter.DjManualJudgeAdapter;
import com.yiren.dbaa.module.exam.view.adapter.DjProjectInfoAdapter;
import com.yiren.dbaa.util.MeterTransferUtil;
import com.yiren.dbaa.util.NoDoubleClickUtil;
import com.yiren.dbaa.view.toast.MessageBox;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lwb
 * @date :2021/11/30 11:54
 * @description: 滴驾考试界面
 */
public class ExamDjActivity extends BaseExamActivity implements DjGradesAdapter.OnDeleteGradeListener, DjManualJudgeAdapter.OnJudgeCheckChangeListener {

    @BindView(R.id.ll_stu_info)
    LinearLayout llStuInfo;     //学员信息布局
    @BindView(R.id.tv_mileage)
    TextView tvMileage;         //行驶里程
    @BindView(R.id.tv_exam_time)
    TextView tvExamTime;        //考试用时
    @BindView(R.id.tv_exam_line)
    TextView tvExamLine;        //线路
    @BindView(R.id.iv_exam_line)
    ImageView ivExamLine;       //线路更多

    @BindView(R.id.rl_car_info)
    RelativeLayout rlCarInfo;   //车辆信息布局
    @BindView(R.id.tv_thirty)
    TextView tvThirty;          //符合特定条件的里程
    @BindView(R.id.iv_gears)
    ImageView ivGears;          //档位
    @BindView(R.id.tv_gears)
    TextView tvGears;
    @BindView(R.id.ll_location)
    LinearLayout llLocation;    //定位
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.ll_angle)
    LinearLayout llAngle;       //角度
    @BindView(R.id.iv_angle)
    ImageView ivAngle;
    @BindView(R.id.tv_angle)
    TextView tvAngle;
    @BindView(R.id.iv_rotate)
    ImageView ivRotate;         //转速
    @BindView(R.id.tv_rotate)
    TextView tvRotate;
    @BindView(R.id.iv_speed)
    ImageView ivSpeed;          //车速
    @BindView(R.id.tv_speed)
    TextView tvSpeed;
    @BindView(R.id.gv_car_signal)
    GridView gvCarSignal;       //车辆信号
    @BindView(R.id.ll_mode_change)
    LinearLayout llModeChange;
    @BindView(R.id.iv_mode)
    ImageView ivMode;
    @BindView(R.id.tv_mode_change)
    TextView tvModeChange;      //白天黑夜模式

    @BindView(R.id.ll_exam_score)
    LinearLayout llExamScore;   //考试得分布局
    @BindView(R.id.tv_exam_score)
    TextView tvExamScore;       //得分
    @BindView(R.id.tv_satellite)
    TextView tvSatellite;       //卫星数

    @BindView(R.id.ll_grade_title)
    LinearLayout llGradeTitle;
    @BindView(R.id.tv_project_title)
    TextView tvProjectTitle;
    @BindView(R.id.tv_cause_title)
    TextView tvCauseTitle;
    @BindView(R.id.tv_score_title)
    TextView tvScoreTitle;
    @BindView(R.id.tv_time_title)
    TextView tvTimeTitle;
    @BindView(R.id.tv_action_title)
    TextView tvActionTitle;
    @BindView(R.id.lv_grades)
    ListView lvGrades;

    @BindView(R.id.ll_exam_bottom1)
    LinearLayout llExamBottom1; //底部显示项目布局
    @BindView(R.id.gv_project)
    GridView gvProject;         //项目列表
    @BindView(R.id.tb_qibu_action)
    ToggleButton tbQibuAction;  //起步
    @BindView(R.id.bt_start_or_end_exam)
    Button btStartOrEndExam;    //开始或结束考试

    @BindView(R.id.ll_exam_bottom2)
    LinearLayout llExamBottom2; //人工评判布局
    @BindView(R.id.tv_manual_grade)
    TextView tvManualGrade;     //人工评判
    @BindView(R.id.ll_judge_title)
    LinearLayout llJudgeTitle;  //人工评判标题
    @BindView(R.id.tv_judge_title)
    TextView tvJudgeTitle;
    @BindView(R.id.tv_reason_title)
    TextView tvReasonTitle;
    @BindView(R.id.tv_grade_title)
    TextView tvGradeTitle;
    @BindView(R.id.tv_select_title)
    TextView tvSelectTitle;
    @BindView(R.id.lv_judge_details)
    ListView lvJudgeDetails;

    /*** 车辆信号适配器车辆信号适配器 */
    private DjCarSignalAdapter carSignalAdapter;
    /*** 项目列表适配器 */
    private DjProjectInfoAdapter projectInfoAdapter;
    /*** 评分适配器 */
    private DjGradesAdapter gradesAdapter;
    /*** 人工评判适配器 */
    private DjManualJudgeAdapter manualJudgeAdapter;

    private int checkPosition = -1;  //人工评判选中的扣分项
    private int curPage = 0;         //人工评判当前页

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam_dj);
        ButterKnife.bind(this);
        initParent();
        setAdapter();
        setData();
        initListener();
        setMode(mode);
        startUpdateStateTask();
    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        /*** 车辆信号适配器 */
        carSignalAdapter = new DjCarSignalAdapter(this, mode);
        gvCarSignal.setAdapter(carSignalAdapter);
        /*** 项目列表适配器 */
        projectInfoAdapter = new DjProjectInfoAdapter(this, projects, projectCodeMap, this);
        gvProject.setAdapter(projectInfoAdapter);
        /*** 人工评判列表适配器 */
        manualJudgeAdapter = new DjManualJudgeAdapter(this, artificialJudges, mode, this);
        lvJudgeDetails.setAdapter(manualJudgeAdapter);
        /*** 评分列表适配器 */
        gradesAdapter = new DjGradesAdapter(this, testRecords, mode, this);
        lvGrades.setAdapter(gradesAdapter);
    }

    private void setData() {
        if (startProjectInfo != null && PointCode.QIBU_CODE.equals(startProjectInfo.getId())) {
            tbQibuAction.setChecked(true);
            tbQibuAction.setEnabled(false);
        } else {
            tbQibuAction.setChecked(false);
            tbQibuAction.setEnabled(true);
        }
        if (null != lineInfo) {
            tvExamLine.setText(lineInfo.getName());
        }
        idStudent.setStudentInfo();
    }

    private void initListener() {
        //人工评判扣分滑动
        lvJudgeDetails.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 判断第一个可见item的位置和当前可见item的和是否等于总item数
                if ((visibleItemCount + firstVisibleItem) != totalItemCount) {
                    // 如果不相等就指定位置为当前可见条数
                    curPage = (visibleItemCount + firstVisibleItem);
                } else {
                    // 如果相等就指定位置为0，用于循环显示
                    curPage = 0;
                }
            }
        });
    }

    /**
     * 刷新页面状态
     */
    private void startUpdateStateTask() {
        stateInfoRunnable = new Runnable() {
            @Override
            public void run() {
                CarStateBean carState = CarStateBean.getInstance();
                GpsInfoBean gps = GpsInfoBean.getInstance();
                tvGears.setText(carState.getGear().getName());
                tvSpeed.setText(StringUtil.format(carState.getSpeed(), StringUtil.GPS_SPEED_FORMAT));
                tvRotate.setText(StringUtil.format(carState.getRotateSpeed(), StringUtil.RORATE_SPEED_FORMAT));
                if (!"".equals(SignalGConstant.cfGpsData)) {
                    llLocation.setVisibility(View.VISIBLE);
                    llAngle.setVisibility(View.GONE);
                    tvLocation.setText((gps.getStatusPosition() == 3 && gps.getStatusDirection() == 3) ? "高精度" : "低精度");
                } else {
                    llLocation.setVisibility(View.GONE);
                    llAngle.setVisibility(View.VISIBLE);
                    tvAngle.setText("" + carState.getNsbsAngleDiff());
                }
                if (isStartExamFlag) {
                    tvExamTime.setText("考试用时：" + DateUtil.showTimeCount(trainingTime, DateUtil.SPLIT_TYPE_COLON));
                    tvMileage.setText("行驶里程：" + MeterTransferUtil.parse2Chinese(trainingMileage));
                    calConditionMileage(carState);
                    iExamViewApi.setConditionMileage(tvThirty, ljTotalMileageValue + jdMileageValue);
                    if (practiceCarCheckConfig.isFailureImEndExam() && totalScore < NumberConstant.PASS_MARK) {
                        runOnUiThread(() -> endExam());
                    }
                    idMap.setTrajectoryInfo(carState, gps);
                }
                runnablePublic(carState, gps);
                stateHandler.postDelayed(this, 50);
            }
        };
        stateInfoRunnable.run();
    }

    /**
     * 设置页面模式
     */
    private void setMode(int mode) {
        ivExamLine.setImageResource(mode == 1 ? R.drawable.triangle_bottom_day_shape : R.drawable.triangle_bottom_night_shape);
        ivGears.setImageResource(mode == 1 ? R.mipmap.day_gears : R.mipmap.night_gears);
        ivLocation.setImageResource(mode == 1 ? R.mipmap.day_location : R.mipmap.night_location);
        ivAngle.setImageResource(mode == 1 ? R.mipmap.day_angle : R.mipmap.night_angle);
        ivRotate.setImageResource(mode == 1 ? R.mipmap.day_rotate : R.mipmap.night_rotate);
        ivSpeed.setImageResource(mode == 1 ? R.mipmap.day_speed : R.mipmap.night_speed);
        ivMode.setImageResource(mode == 1 ? R.mipmap.day_mode : R.mipmap.night_mode);
        tvModeChange.setText(mode == 1 ? "白天" : "夜间");
        setInterfaceMode(mode);
        carSignalAdapter.setMode(mode);
        manualJudgeAdapter.setMode(mode);
    }

    /**
     * 设置页面模式
     *
     * @param mode 1：白天模式 2：夜间模式
     */
    private void setInterfaceMode(int mode) {
        idMap.getLlExamMain().setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_main_day : R.color.exam_main_night));
        llStuInfo.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_people_day : R.color.exam_people_night));
        idStudent.setTvStuNameColor(mode);
        tvExamLine.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        tvExamTime.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        rlCarInfo.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_people_day : R.color.exam_people_night));
        tvMileage.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        tvThirty.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        tvGears.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        tvAngle.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        tvRotate.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        tvSpeed.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        llModeChange.setBackgroundResource(mode == 1 ? R.drawable.exam_mode_day_shape : R.drawable.exam_mode_night_shape);
        llExamScore.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_score_day : R.color.exam_people_night));
        llGradeTitle.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_sub_color : R.color.exam_main_night));
        tvProjectTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        tvCauseTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        tvScoreTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        tvTimeTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        tvActionTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
//        tvActionTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        lvGrades.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_grade_day : R.color.exam_grade_night));
        llExamBottom2.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.judge_bg_day : R.color.judge_bg_night));
        tvManualGrade.setTextColor(getResources().getColor(mode == 1 ? R.color.exam_txt : R.color.white));
        llJudgeTitle.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_sub_color : R.color.exam_main_night));
        tvJudgeTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        tvReasonTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        tvGradeTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        tvSelectTitle.setTextColor(getResources().getColor(mode == 1 ? R.color.black : R.color.white));
        lvJudgeDetails.setBackgroundColor(getResources().getColor(mode == 1 ? R.color.exam_grade_day : R.color.exam_grade_night));
    }

    @OnClick({R.id.iv_stu_change, R.id.ll_exam_line, R.id.ll_mode_change, R.id.ll_traject_preview, R.id.ll_people_judge, R.id.ll_qibu_action, R.id.bt_start_or_end_exam, R.id.bt_exit_exam, R.id.ll_rotate_page, R.id.ll_reduce_score, R.id.ll_return})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_stu_change:  //切换学员
                if (isStartExamFlag) {
                    MessageBox.show(this, "请先结束考试，再切换学员");
                    return;
                }
                idStudent.openStudentDrawer();
                idStudent.getQrCode(model);
                break;
            case R.id.ll_exam_line:   //选择线路
                if (isStartExamFlag) {
                    MessageBox.show(this, "请先结束考试，再切换线路");
                    return;
                }
                ivExamLine.setImageResource(mode == 1 ? R.drawable.triangle_up_day_shape : R.drawable.triangle_up_night_shape);
                showLineSelectDialog((isChange) -> {
                    if (isChange) tvExamLine.setText(lineInfo.getName());
                    ivExamLine.setImageResource(mode == 1 ? R.drawable.triangle_bottom_day_shape : R.drawable.triangle_bottom_night_shape);
                });
                break;
            case R.id.ll_mode_change:  //模式切换
                mode = mode == 1 ? 2 : 1;
                setMode(mode);
                break;
            case R.id.ll_traject_preview: //轨迹预览
                if (isStartExamFlag) {
                    idMap.clickPreview();
                } else {
                    MessageBox.show(this, "请先开始考试，再使用轨迹预览！");
                }
                break;
            case R.id.ll_people_judge:   //人工评判
                if (isStartExamFlag) {
                    if (null == projects || projects.size() == 0) {
                        MessageBox.show(this, "项目列表为空！");
                        return;
                    }
                    llExamBottom1.setVisibility(View.GONE);
                    llExamBottom2.setVisibility(View.VISIBLE);
                } else {
                    MessageBox.show(this, "请开始考试后再使用人工指令");
                }
                break;
            case R.id.ll_qibu_action:  //直接起步
                if (isStartExamFlag) {
                    MessageBox.show(this, "请先结束考试");
                } else if (!tbQibuAction.isEnabled()) {
                    MessageBox.show(this, "第一个项目选择起步，本按钮不可关闭！");
                } else {
                    tbQibuAction.setChecked(!tbQibuAction.isChecked());
                    if (tbQibuAction.isChecked()) {
                        startProjectInfo = iExamProjectApi.loadStartPointInfo(3, lightProjects);
                    } else {
                        startProjectInfo = iExamProjectApi.loadStartPointInfo(practiceCarCheckConfig.getStartExamProject(), lightProjects);
                    }
                }
                break;
            case R.id.bt_start_or_end_exam://开始或结束考试
                if (!NoDoubleClickUtil.isDoubleClick()) {
                    if (!isStartExamFlag) {
                        if (null == idStudent.getStudentBean()) {
                            MessageBox.show(this, "请先选择学员");
                            return;
                        }
                        if (lineInfo == null) {
                            MessageBox.show(this, "请先选择一条线路");
                            return;
                        }
                        isStartExamFlag = true;
                        btStartOrEndExam.setText("结束考试");
                        if (null != startProjectInfo) {
                            startExamPublic();
                            refreshGradeState();
                        }
                    } else {
                        endExam();
                    }
                }
                break;
            case R.id.bt_exit_exam:    //退出考试
                if (isStartExamFlag) {
                    CommonDialog.show(this, "提示", "确定退出考试吗？", (dialog, which) -> {
                        dialog.dismiss();
                        exitExam();
                    });
                } else {
                    finish();
                }
                break;
            case R.id.ll_rotate_page:  //翻页
                lvJudgeDetails.setSelection(curPage); // 选择到指定的item
                break;
            case R.id.ll_reduce_score: //扣分
                if (checkPosition == -1) {
                    MessageBox.show(this, "请选中一条扣分");
                } else if (checkPosition < artificialJudges.size()) {
                    addGradeRecord(artificialJudges.get(checkPosition));
                    refreshGradeState();
                    checkPosition = -1;
                    manualJudgeAdapter.setCheckPosition(checkPosition);
                }
                break;
            case R.id.ll_return:  //人工评判返回
                llExamBottom1.setVisibility(View.VISIBLE);
                llExamBottom2.setVisibility(View.GONE);
                checkPosition = -1;
                manualJudgeAdapter.setCheckPosition(checkPosition);
                break;
        }
    }

    /**
     * 结束考试
     */
    private void endExam() {
        btStartOrEndExam.setText("开始考试");
        resetProjectState();
        super.endExamPublic();
    }

    /**
     * 退出考试
     */
    private void exitExam() {
        finish();
        super.exitExamPublic();
    }

    /**
     * 结束考试(重置项目状态)
     */
    private void resetProjectState() {
        projectCodeMap.clear();
        for (int i = 0; i < projects.size(); i++) {
            projects.get(i).setTaskState(null);
        }
        projectInfoAdapter.notifyDataSetChanged();
    }

    /**
     * 人工评判选择改变的回调
     */
    @Override
    public void onJudgeCheckChange(int position) {
        checkPosition = position;
    }

    /**
     * 删除扣分的回调
     */
    @Override
    public void onDeleteGrade(int position) {
        if (isStartExamFlag) {
            deleteGradeRecord(position);
            refreshGradeState();
        } else {
            MessageBox.show(this, "结束考试不能删除扣分！");
        }
    }

    @Override
    public void refreshParameter() {
        iExamViewApi.setConditionMileage(tvThirty, 0);
    }

    @Override
    public void refreshProjectState() {
        projectInfoAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshGradeState() {
        tvExamScore.setText(totalScore + "分");
        gradesAdapter.notifyDataSetChanged();
        projectInfoAdapter.notifyDataSetChanged();
    }

    @Override
    public void endExamRefreshState() {
        endExam();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetProjectState();
        if (isStartExamFlag) exitExam();
    }
}
